package com.dys.hejiayuncommunity.system.service.impl;

import com.dys.hejiayuncommunity.common.core.exception.BaseException;
import com.dys.hejiayuncommunity.common.enums.UserStatus;
import com.dys.hejiayuncommunity.framework.service.SysPermissionService;
import com.dys.hejiayuncommunity.system.domain.LoginUser;
import com.dys.hejiayuncommunity.system.domain.SysUser;
import com.dys.hejiayuncommunity.system.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @className: com.dys.hejiayuncommunity.system.service.impl.UserDetailsServiceImpl
 * @description: 根据用户名查询用户信息实现
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/12/19 21:38
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.根据用户名查询用户信息
        SysUser user = sysUserService.findUserByUsername(username);

        // 2.非空判断
        if (Objects.isNull(user)) {
            logger.info("登录用户:{} 不存在", username);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            logger.info("登录用户: {} 已被停用", username);
            throw new BaseException("对不起,您的账号：" + username + "已被停用");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            logger.info("登录用户: {} 已被删除", username);
            throw new BaseException("对不起,您的账号：" + username + "已被停用");
        }
        return createLoginUser(user);
    }

    /**
     * 创建登录用户
     *
     * @param user 用户信息
     * @return 用户详情
     */
    private UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user,sysPermissionService.getMenuPermission(user));
    }
}
